<script setup lang="ts">
import HandsonTable from 'handsontable'
import { registerAllModules } from 'handsontable/registry'
import 'handsontable/styles/handsontable.css'
import 'handsontable/styles/ht-theme-main.css'
import '@/style/handsontable-theme.css'
import { registerLanguageDictionary, zhCN } from 'handsontable/i18n'
import { HyperFormula } from 'hyperformula'
import { REPORT_FORM_ID, REPORT_ID } from '@/enum'

import type { LoadDataResponse } from './type'
import useTheme from '../useTheme'
import { HEADER_CELL_CLASS, READONLY_CELL_CLASS, ROUND_NUMBER as _ROUND_NUMBER } from '../config'
import useLoadReportDetail from './useLoadReportDetail'

defineOptions({ name: 'SummaryCompanyPrimaryElectricityDevice4' })

const props = defineProps<{
  time: string
}>()

const ROUND_NUMBER = _ROUND_NUMBER + 2

registerLanguageDictionary(zhCN)

// register Handsontable's modules
registerAllModules()

const HEADERS = [
  ['主井皮带', null, null, null, null, null, null, null, null, null, null],
  [
    '单位名称',
    '装机容量（kw）',
    '起码',
    '止码',
    '耗电量（千瓦时）',
    '主井皮带电耗',
    '过煤量',
    '垂直位移量',
    '换算系数',
    '水平位移量',
    '工序能耗',
  ],
]
const FOOTERS = [
  [
    '备注',
    '主提升带式输送系统工序能耗指标：能耗值【KWH/(T.HM)】一级≤0.38；二级0.381-0.45；三级0.451-0.55',
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
  ],
]
const DEFAULT_MERGE_CELLS = [
  { row: 0, col: 0, rowspan: 1, colspan: 11 },
]

const wrapper = ref<HTMLElement>()
const hot = ref<HandsonTable>()
// 主井皮带
// eslint-disable-next-line
const reportId = REPORT_ID.MAIN_ENERGY_CONSUMING_EQUIPMENT_STATISTICS_SUMMARY

const formId = REPORT_FORM_ID.SUMMARY_MAIN_SHAFT_BELT
// 当前企业名称
// eslint-disable-next-line
const tenantName = ref('')
// 远程数据
const loadDataResponse = shallowRef<LoadDataResponse>()
const { res, loadReportData } = useLoadReportDetail()

async function loadData() {
  if (!props.time)
    return
  await loadReportData(props.time, unref(formId))
  const src = loadDataResponse.value = unref(res)
  const equipmentList = src?.equipmentList ?? []
  const dataList = []
  let cur = HEADERS.length + 1
  for (let i = 0; i < equipmentList.length; i++) {
    const equipment = equipmentList[i]
    const length = equipment.dataList?.length ?? 0
    for (let j = 0; j < length; j++) {
      const array: Array<string | number | null> = [
        j === 0 ? equipment.subsidiaryName : null,
      ]
      const v = equipment.dataList[j]
      array.push(
        v.installedCapacity,
        v.startQuantity,
        v.endQuantity,
        v.electricQuantity,
        // 主井皮带电耗
        j === 0 ? equipment.zjpdZjpddh : null,
        // 过煤量
        j === 0 ? equipment.zjpdGml : null,
        // 垂直位移量
        j === 0 ? equipment.zjpdCzwyl : null,
        // 换算系数
        j === 0 ? equipment.zjpdHsxs : null,
        // 水平位移量
        j === 0 ? equipment.zjpdSpwyl : null,
        // 工序能耗用公式去计算
        `=IFERROR(ROUND((SUM(E${cur}:E${cur + length - 1}))*100/(G${cur}*(H${cur}+I${cur}*J${cur})),${ROUND_NUMBER}),"")`,
      )
      dataList.push(array)
    }
    cur += length
  }

  const data = [
    ...HEADERS,
    ...dataList,
    ...FOOTERS,
  ]
  hot.value?.loadData(data)
}

function updateMergeCells() {
  if (hot.value) {
    const src = loadDataResponse.value
    if (src) {
      const initial = HEADERS.length
      let m = initial
      let row = 0
      // 头部
      const mergeCells = [...DEFAULT_MERGE_CELLS]
      for (let i = 0; i < src.equipmentList.length; i++) {
        const equipment = src.equipmentList[i]
        const dataList = equipment.dataList ?? []
        for (let j = 0; j < dataList.length; j++) {
          if (j === 0) {
            row = m
            // 索引为0，5，6，7，8，9，10的列需要根据数据行数来纵向合并单元格
            mergeCells.push(
              { row, col: 0, rowspan: dataList.length, colspan: 1 },
              { row, col: 5, rowspan: dataList.length, colspan: 1 },
              { row, col: 6, rowspan: dataList.length, colspan: 1 },
              { row, col: 7, rowspan: dataList.length, colspan: 1 },
              { row, col: 8, rowspan: dataList.length, colspan: 1 },
              { row, col: 9, rowspan: dataList.length, colspan: 1 },
              { row, col: 10, rowspan: dataList.length, colspan: 1 },
            )
          }
          m++
        }
      }
      // 最后一行
      mergeCells.push({ row: m, col: 1, rowspan: 1, colspan: 10 })
      // 更新
      hot.value.updateSettings({
        mergeCells,
        cell: [
        // 最后一行备注内容"居左对齐"
          { row: m, col: 1, className: 'htLeft' },
        ],
      })
    }
  }
}

async function init() {
  if (!wrapper.value)
    return
  hot.value = new HandsonTable(wrapper.value, {
    fixedRowsTop: HEADERS.length,
    cells(row) {
      if (row < HEADERS.length) {
        return { className: `htCenter htMiddle ${HEADER_CELL_CLASS}` }
      }
      return {}
    },
    readOnly: true,
    // disableVisualSelection: props.readonly,
    language: zhCN.languageCode,
    data: [
      ...HEADERS,
      ['', '', '', '', '', '', '', '', '', '', ''],
      ['', '', '', '', null, null, null, null, null, null, null],
      ['', '', '', '', null, null, null, null, null, null, null],
      ...FOOTERS,
    ],
    formulas: {
      engine: HyperFormula,
    },
    className: 'htCenter htMiddle',
    readOnlyCellClassName: READONLY_CELL_CLASS,
    stretchH: 'all',
    // autoColumnSize: true,
    colWidths: 100,
    manualColumnResize: true,
    colHeaders: true,
    rowHeaders: true,
    contextMenu: false,
    mergeCells: [],
    cell: [{ row: 5, col: 1, className: 'htLeft' }],
    licenseKey: 'non-commercial-and-evaluation',
  })

  // debug
  if (import.meta.env.VITE_REPORT_DEBUG === '1') {
    hot.value.addHook('afterSelection', (row, col) => {
      if (row > -1 && col > -1) {
        console.info(`[${row},${col}] ${hot.value?.getSourceDataAtCell(row, col)}`)
        document.execCommand('copy')
      }
    })
  }
}

async function bootstrap() {
  init()
  await loadData()
  await nextTick()
  updateMergeCells()
}

const { isDark } = useTheme(async () => {
  if (hot.value) {
    hot.value.destroy()
    hot.value = undefined
    await nextTick()
    await bootstrap()
  }
})

onMounted(bootstrap)
</script>

<template>
  <div class="h-full w-full">
    <div
      ref="wrapper" class="h-full w-full overflow-auto" :class="{
        'ht-theme-main-dark': isDark,
        'ht-theme-main': !isDark,
      }"
    />
  </div>
</template>
